<?php
/**
 * Copyright 2013 Marek Kaszewski
 *
 * This file is part of the JHUB1 Online Community Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Jhub1_Common\Entity\BO;

use Jhub1_Common\Entity\BO\AbstractBO;
use Jhub1_Common\Entity\Users as Users;
use Jhub1_Common\Entity\OfGroup;
use Jhub1_Common\Entity\OfGroupProp;
use Jhub1_Common\Model\SettingsObjects\DateTimeObject;
use Jhub1_Common\Model\SettingsObjects\UserConfigurationObject;
use Jhub1_Common\Model\SettingsObjects\UserLocalizationObject;
use Jhub1_Common\Model\SettingsObjects\UserConsoleSettingsObject;
use Jhub1_Common\Model\Key\UniqueKey;

class UsersBO extends AbstractBO
{
    private $userPO = null;
    private $serviceLocator;

    private $props = array(
        'sharedRoster.showInRoster' => 'nobody',
        'sharedRoster.displayName' => '',
        'sharedRoster.groupList' => ''
    );

    public function __construct($serviceLocator)
    {
        $this->getEM($serviceLocator);
        $this->serviceLocator = $serviceLocator;
    }

    public function getUserPO()
    {
        return $this->userPO;
    }

    public function insertUser($data)
    {
        $kg = new UniqueKey($this);
        $emailActivationKey = $kg->getActivationUUID();
        $groupId = $kg->getGroupUUID();
        $this->em->getConnection()->beginTransaction();
        try {
            $user = new Users();
            $user->setId($kg->getUUID());
            $user->setEmail($data['email']);
            $user->setPassword(md5($data['password']));
            $user->setGroupId($groupId);
            $user->setActivationCode($emailActivationKey);
            $user->setUserType(0);
            if(isset($data['status'])) {
                $user->setStatus($data['status']);
            } else {
                $user->setStatus(0);
            }
            $user->setLocalization(new UserLocalizationObject());
            $user->setConfiguration(new UserConfigurationObject());
            $user->setConsoleSettings(new UserConsoleSettingsObject());
            $this->em->persist($user);
            $this->em->flush();

            $group = new OfGroup();
            $group->setDescription($data['email']);
            $group->setGroupName($groupId);
            $this->em->persist($group);
            $this->em->flush();

            foreach ($this->props as $key => $val) {
                $groupProp = new OfGroupProp();
                $groupProp->setGroupName($groupId);
                $groupProp->setName($key);
                $groupProp->setValue($val);
                $this->em->persist($groupProp);
                $this->em->flush();
            }
            $this->updateID(25, 2);
            //update 25,6 ID +2
            $this->em->getConnection()->commit();
        } catch (Exception $e) {
            $this->em->getConnection()->rollback();
            $this->em->close();
            throw $e;
        }

        $this->userPO = $user;
        return $user;
    }

    private function updateID($type, $incOffset)
    {
        $id = $this->em->getRepository('\Jhub1_Common\Entity\OfId')->find($type);
        $counter = $id->getId();
        $counter = $counter + $incOffset;
        $id->setId($counter);
        $this->em->persist($id);
        $this->em->flush();
    }

    public function deleteUser($user)
    {
/*        $this->em->getConnection()->beginTransaction();
        try {
            $this->em->getConnection()->commit();
        } catch (Exception $e) {
            $this->em->getConnection()->rollback();
            $this->em->close();
            throw $e;
        }*/
            //$this->em->remove($this->campaign);
        //$this->em->flush();
    }

    public function setResendCode($userPO, $resendCode)
    {
        $userPO->setResendActivationCode($resendCode);
        $this->em->persist($userPO);
        $this->em->flush();
    }

    private function activateUser($user)
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->find($user->getId());
        $user->setStatus(1);
        $this->em->persist($user);
        $this->em->flush();
    }

    public function isNewUser()
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->find($this->userPO->getId());
        $status = $user->getStatus();
        $code = $user->getActivationCode();
        if ($status == 1 && strlen($code) > 0) {
            $user->setActivationCode("");
            $this->em->persist($user);
            $this->em->flush();
            return true;
        }
        return false;
    }

    public function activateUserFromEmail($code)
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->findOneBy(array('activationcode' => $code));
        if ($user instanceof  \Jhub1_Common\Entity\Users) {
            $this->activateUser($user);
            return $user;
        }
        return null;
    }

    public function deActivateUser($user)
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->find($user->getId());
        $user->setStatus(0);
        $this->em->persist($user);
        $this->em->flush();
    }

    public function getUserByGroupId($groupId)
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->findOneBy(array('groupid' => $groupId));
        if ($user instanceof  \Jhub1_Common\Entity\Users) {
            return $user;
        }
        return null;
    }

    public function getUserByEmail($email)
    {
        $user = $this->em->getRepository('\Jhub1_Common\Entity\Users')->findOneBy(array('email' => $email));
        if ($user instanceof  \Jhub1_Common\Entity\Users) {
            return $user;
        }
        return null;
    }

    public function hydrate($deHydratedUserPO)
    {
        $this->userPO = $this->getUserByEmail($deHydratedUserPO->getEmail());
    }

    public function updateLastLoginDate($user)
    {
        $user->setLastLogin(new DateTimeObject());
        $this->em->persist($user);
        $this->em->flush();
    }

    public function isValidUser($user)
    {
        if ($user instanceof  \Jhub1_Common\Entity\Users) {
            return true;
        }
        return false;
    }

    public function getUserByEmailAndPassword($email, $password)
    {
        $user = $this->getUserByEmail($email);
        if (null == $user) {
            return null;
        }
        if ($user->getPassword() == md5($password)) {
            return $user;
        }
        return null;
    }

    public function isPKUnique($primaryKey)
    {
        if(null == $this->em->getRepository('\Jhub1_Common\Entity\Users')->find($primaryKey)) {
            return true;
        }
        return false;
    }

    public function isGroupIdUnique($groupId)
    {
        if (null == $this->getUserByGroupId($groupId)) {
            return true;
        }
        return false;
    }

    public function isActivationIdUnique($code)
    {
        if(null == $this->em->getRepository('\Jhub1_Common\Entity\Users')->findOneBy(array('activationcode' => $code))) {
            return true;
        }
        return false;
    }

    public function getServiceLocator()
    {
        // TODO: Implement getServiceLocator() method.
    }

    public function getObjectByUUID($uuid)
    {
        return $this->em->getRepository('\Jhub1_Common\Entity\Users')->find($uuid);
    }
}